<template>
  <div>
    <SelectUser :selectedIds="selectedIds" :multiple="true" @change="submit">
      <a-button type="primary">{{ t('添加人员') }}</a-button>
    </SelectUser>
  </div>
</template>

<script setup lang="ts">
  import { computed } from 'vue';
  import { getUserMulti } from '/@/api/system/user';
  import { SelectUser } from '/@/components/SelectOrganizational/index';
  import { MemberType } from '/@/enums/workflowEnum';
  import { MemberConfig } from '/@/model/workflow/memberSetting';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const emits = defineEmits(['change']);
  const props = withDefaults(
    defineProps<{
      memberList: Array<MemberConfig>;
    }>(),
    {
      memberList: () => {
        return [];
      },
    },
  );
  let selectedIds = computed(() => {
    if (props.memberList && props.memberList.length > 0) {
      return props.memberList
        .filter((ele: MemberConfig) => {
          return ele.memberType === MemberType.USER;
        })
        .map((ele: MemberConfig) => {
          return ele.id;
        });
    } else {
      return [];
    }
  });

  async function submit(ids: Array<string>) {
    let list: Array<MemberConfig> = [];
    if (props.memberList && props.memberList.length > 0) {
      props.memberList.forEach((ele) => {
        if (ele.memberType != MemberType.USER)
          list.push({
            name: ele.name,
            id: ele.id,
            memberType: ele.memberType,
          });
      });
    }
    let users = await getUserMulti(ids.join(','));
    if (users.length > 0) {
      users.forEach((ele) => {
        list.push({
          name: ele.name,
          id: ele.id,
          memberType: MemberType.USER,
        });
      });
    }
    emits('change', list);
  }
</script>
